package cn.ljh.zard.executor;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;
import java.util.function.Supplier;

/**
 * 基础的
 */
@Slf4j
public class AbBaseExecutor implements BaseExecutor {


    // 最大容量
    private final static Integer maxCapacity = 20;
    // 默认的线程池
    ThreadPoolExecutor cacheThreadPool = new ThreadPoolExecutor(0, maxCapacity,
            60L, TimeUnit.SECONDS,
            new SynchronousQueue<Runnable>(),
            new ZardThreadFactory());




    /**
     * 是否可执行 almost do it
     *
     * @return 当前是否可以执行
     */
    @Override
    public boolean isReadly() {
        boolean shutdown = cacheThreadPool.isShutdown();
        return !shutdown;
    }

    /**
     * 执行
     *
     * @return 同步返回结果
     */
    @Override
    public <T> T doRun(Supplier supplier) {
        Future<T> getD = cacheThreadPool.submit(() -> (T) supplier.get());
        try {
            return getD.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 异步处理
     *
     * @return 异步返回结果
     */
    @Override
    public <T> Future<T> doAsyncRun(Supplier supplier) {

        Future<T> getD = cacheThreadPool.submit(() -> {

            Object o = supplier.get();
            log.info(o.toString());
            return (T) o;
        });

        return getD;
    }


    /////////////// implements Parse.class


}

